<template>
    <view class="list">
        <view class="item tou-item">
            头像
            <button class="tou" open-type="chooseAvatar" @click="onChooseAvatar">
                <image class="tou" :src="'data:image/png;base64,' + userInfo.avatar"/>
            </button>
            <text class="jump"></text>
        </view>
        <view class="item" @tap="username" data-field="username">
            名称
            <text class="text">{{ userInfo.userName }}</text>
            <text class="jump">〉</text>
        </view>
        <view class="item" @tap="sex">
            性别
            <text class="text">{{ userInfo.sex == '0' ? '男' : userInfo.sex == '1' ? '女' : '未知' }}</text>
            <text class="jump">〉</text>
        </view>
        <view class="item" @tap="addressFun">
            收货地址
            <text class="text">{{ address == '' ? '添加地址' : address.address }}</text>
            <text class="jump">〉</text>
        </view>
    </view>
</template>

<script>
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
export default {
    data() {
        return {
            userInfo: {
                avatar: '',
                userName: '',
                sex: ''
            },
            address: {
                address: ''
            }
        };
    },
    onShow: function () {
      if (uni.getStorageSync('user')) {
        this.onShowClone3389();
      }else {
        uni.navigateBack();
      }
    },
    methods: {
        onShowClone3389: function () {
            var that = this;
            let userInfo = uni.getStorageSync('user');
            var allAddress = uni.getStorageSync('address');
            var address = '';
            that.setData({
                userInfo: userInfo
            });
            for (var i = 0; i < allAddress.length; i++) {
                if (allAddress[i].checked) {
                    address = allAddress[i];
                    break;
                }
            }
            if (address == '' && allAddress.length > 0) {
                address = allAddress[0];
            }
            that.setData({
                address: address
            });
        },

        username: function () {
            uni.navigateTo({
                url: '/pages/userdata/username/index'
            });
        },

        sex: function () {
            uni.navigateTo({
                url: '/pages/userdata/sex/index'
            });
        },

        addressFun: function () {
            uni.navigateTo({
                url: '/pages/address/index'
            });
        },
        getUrlParams(name) {
          let local = location.href; 
          var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");				
          if (reg.test(local)) {
            return unescape(RegExp.$2.replace(/\+/g, " "));
          }
          return "";
        },
        // 微信授权
        wxAuthorization() {
          let code = this.getUrlParams("code");
          //是否存在code
          //如果不存在code则跳转授权
          if (!code) {
            // 本地路径
            let local = `http://jkhmzw.shudingkj.com/pages/userdata/index`
            // 公众号或测试号appid 
            let appid = config.APPID;
            //不存在就打开下面的地址进行授权
            let authPageBaseUri = "https://open.weixin.qq.com/connect/oauth2/authorize";
            let scope = 'snsapi_userinfo';
            authPageBaseUri +='?appid='+ appid+'&redirect_uri='+encodeURIComponent(local)+'&response_type=code&scope='+scope+'&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
            window.location.href = authPageBaseUri;
          }else {
            let appid = config.APPID;
            let secret= '26fd8e0d4fe102b8e37fc421f1277684';
            let authPageBaseUri = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
            uni.request({
              method: 'POST',
              url: authPageBaseUri,
              success: (res) => {
                  let token = res.refresh_token;
                  let openid = res.openid;
                  let url = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openid+"&lang=zh_CN";
                  uni.request({
                    method: 'POST',
                    url: url,
                    success: (resUser) => {
                      this.userInfo.userName = resUser.nickname;
                      this.userInfo.sex = resUser.sex;
                      this.userInfo.avatar = resUser.headimgurl;
                    }
                  });
              }     
            });
          }
        },
        onChooseAvatar: function (e) {            
            var that = this;
            let userInfo = uni.getStorageSync('user');            
            uni.chooseImage({
                count: 1,
                // 默认9
                sizeType: ['original', 'compressed'],
                // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    that.updateUseravatar(userInfo.userId, res.tempFilePaths);
                }
            });
        },

        updateUseravatar: function (userId, userAvatar) {
            var that = this;
            let userInfo = uni.getStorageSync('user');
            uni.uploadFile({
                url: config.clubApi.putAvatar,
                filePath: userAvatar,
                method: 'POST',
                name: 'file',
                header: {
                    'Content-Type': 'multipart/form-data'
                },
                formData: {
                    userId: userId
                },
                success(res) {
                    if (res.statusCode === 200) {
                        let json = JSON.parse(res.data);
                        userInfo.avatar = json.data;
                        uni.setStorageSync('user', userInfo);
                        that.setData({
                            userInfo: userInfo
                        });
                        util.showSuccess('设置成功!', config.showSuccessTime, () => {
                            that.onShowClone3389({});
                        });
                    }
                }
            });
        }
    }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
